package com.lpc.framework.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

public class VoConverters {
    private static final Logger LOGGER = LoggerFactory.getLogger(VoConverters.class);

    public static <A, B> List<B> convertList(List<A> from, Class<B> to) {
        List<B> creDtos = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(from)) {
            for (A a : from) {
                creDtos.add(VoConverters.convert(a, to));
            }
        }
        return creDtos;
    }

    /**
     * 用于各种vo、domain之间的转换 用法：vo、domain之间的属性取名保持相同
     * 
     * @param from
     * @param to
     * @return
     */
    public static <A, B> B convert(A from, Class<B> to) {
        if (from == null) {
            return null;
        }
        B rst = null;
        try {
            rst = to.newInstance();

            Map<String, Field> toMap = getFields(to);
            Map<String, Field> fromMap = getFields(from.getClass());
            Set<Entry<String, Field>> toSet = toMap.entrySet();
            for (Entry<String, Field> entry : toSet) {
                String key = entry.getKey();
                Field toField = entry.getValue();
                if (!toField.isSynthetic() && fromMap.containsKey(key)) {
                    Object value = getValue(from, key);
                    if (value != null) {

                        Type toType = toField.getGenericType();
                        Field fromField = fromMap.get(key);
                        Type fromType = fromField.getGenericType();

                        if (toType.equals(fromType)) {
                            PropertyUtils.setProperty(rst, key, value);
                        } else if (BigDecimal.class.isInstance(value) && toField.getType().equals(String.class)) {
                            // 从BigDecimal 转成String，特殊处理
                            PropertyUtils.setProperty(rst, key, value.toString());
                        } else if (String.class.isInstance(value) && toField.getType().equals(BigDecimal.class)) {
                            PropertyUtils.setProperty(rst, key, new BigDecimal((String) value));
                        }
                    }
                }
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            LOGGER.error(MessageFormat.format("从{0}转换成{1}失败", from, to.getName()), e);
            throw new RuntimeException("vo转换失败");
        }
        return rst;
    }

    private static <A> Object getValue(A from, String key) throws IllegalAccessException, InvocationTargetException {
        Object value = null;
        try {
            value = PropertyUtils.getProperty(from, key);
        } catch (NoSuchMethodException e) {
            LOGGER.warn(MessageFormat.format("属性{0}无readMethod", key), e);
        }
        return value;
    }

    private static Map<String, Field> getFields(Class<?> to) {
        Map<String, Field> map = new HashMap<String, Field>();
        Field[] fields = to.getDeclaredFields();
        Class<?> pcl = to.getSuperclass();
        while (!pcl.equals(Object.class)) {
            fields = (Field[]) ArrayUtils.addAll(fields, pcl.getDeclaredFields());
            pcl = pcl.getSuperclass();
        }
        for (Field field : fields) {
            map.put(field.getName(), field);
        }
        return map;
    }
}
